<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .router-link-active{
      background: red;
    }
  </style>
</head>
<body>
  <div id="app">
    <router-link tag="button" to="/home">
      首页
    </router-link>
    <router-link tag="button" to="/news">
      新闻
    </router-link>
    <router-link tag="button" to="/about">
      关于我们
    </router-link>
    <h1>我是单页面应用</h1>
    <router-view></router-view>
  </div>
  <script src="vue.js"></script>
  <script src="vue-router.js"></script>
  <script>
    /* 
    
    /home home页
    /new news页
    /about about
     */
    const Home = {
      template: `
        <div>
          <h1> home页 </h1>
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h1> 新闻页 </h1>
        </div>
      `
    }
    const About = {
      template: `
        <div>
          <h1> 关于我们页 </h1>
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <button @click="login">登录</button>
        </div>
      `,
      methods: {
        login(){
          // token 加密  diwhd9e39wdhcit4re-39ue
          setTimeout(()=>{
            const token = "dwiudwo3r3r4ferfe";
            // 存储token
            localStorage.setItem('access_token', token)
            if( this.$route.params.from ){
              this.$router.push(this.$route.params.from)
            }else{
              this.$router.push('/home')
            }
          },500)
        }
      }
    }
    // 以上称为 路由组件 需要在 路由 配置中 挂载
    // 定义路由
    const routes = [ // 路由规则
     /*  {
        path: '/',
        component: Home
      }, */
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        name:'首页',
        component: Home
      },
      {
        path: '/news',
        name:'新闻',
        component: News
      },
      {
        path: '/about',
        name: '关于我们',
        component: About,
        beforeEnter: (to, from, next) => {
          /* 
          直接判断是否登录即可
           */
          const access_token = localStorage.getItem('access_token')

          if(access_token){
            next()
          }else{
            next('/login')
          }
        }
      },
      {
        path: '/login',
        name:'登录',
        component: Login
      }
    ]
    const router = new VueRouter({
      // mode: 'hash',
      routes
    })
   
    const vm = new Vue({
      el: '#app',
      router
    })
  </script>
</body>
</html>